package com.huike.clues.service.impl;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huike.clues.domain.SysOperLog;
import com.huike.clues.domain.dto.SysOperLogPage;
import com.huike.clues.mapper.SysOperLogMapper;
import com.huike.clues.service.ISysOperLogService;
import com.huike.common.core.domain.AjaxResult;
import com.huike.common.core.page.TableDataInfo;
import com.huike.common.result.Result;
import com.huike.common.utils.poi.ExcelUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Description SysOperLogServiceImpl
 * @Author guan
 * @Date 2023-19:28-16
 */
@Service
public class SysOperLogServiceImpl implements ISysOperLogService {
    @Resource
    private SysOperLogMapper sysOperLogMapper;
    @Override
    public TableDataInfo<List<SysOperLog>> findPage(SysOperLogPage sysOperLogPage) {
        Page<SysOperLog> page = new Page<>(sysOperLogPage.getPageNum(), sysOperLogPage.getPageSize());

        LambdaQueryWrapper<SysOperLog> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        if (sysOperLogPage.getParams().get("beginTime")!=null && !(sysOperLogPage.getParams().get("beginTime").equals(""))
                && sysOperLogPage.getParams().get("endTime")!= null && !(sysOperLogPage.getParams().get("endTime").equals("")))
    {
        String benginTime = (String) sysOperLogPage.getParams().get("beginTime");
        LocalDateTime beginDateTime = LocalDateTime.of(LocalDate.parse(benginTime), LocalTime.MIN);
        String endTime =(String) sysOperLogPage.getParams().get("endTime");
        LocalDateTime endDateTime = LocalDateTime.of(LocalDate.parse(endTime), LocalTime.MAX) ;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        lambdaQueryWrapper.ge(SysOperLog::getOperTime,beginDateTime.format(formatter));
        lambdaQueryWrapper.le(SysOperLog::getOperTime,endDateTime.format(formatter));
    }
        lambdaQueryWrapper.like(sysOperLogPage.getKeyWord()!= null ,SysOperLog::getOperName,sysOperLogPage.getKeyWord())
                .like(SysOperLog::getRequestMethod,sysOperLogPage.getKeyWord())
                .like(SysOperLog::getTitle,sysOperLogPage.getKeyWord());
        sysOperLogMapper.selectPage(page,lambdaQueryWrapper);
        TableDataInfo<List<SysOperLog>> dataInfo = new TableDataInfo<>();
        dataInfo.setCode(200);
        dataInfo.setMsg("查询成功");
        dataInfo.setTotal(page.getTotal());
        dataInfo.setRows(page.getRecords());


        return dataInfo;
    }
    /**
     * 删除日志
     * @param ids
     * @return
     */
    @Override
    public Result deleteByIds(List<Long> ids) {
        int row = sysOperLogMapper.deleteBatchIds(ids);
        return Result.success(row);
    }

    /**
     * 日志清空
     * @return
     */
    @Override
    public void deleteAllClen() {
        sysOperLogMapper.deleteAll();
    }
    /**
     * 导出操作报表
     * @param response
     */
    @Override
    public AjaxResult exportBusinessData(HttpServletResponse response) {

//        String url = "D:\\javaspace\\itheima\\sky-take-out\\sky-server\\src\\main\\resources\\运营数据报表模板.xlsx";
        // 查询日志总条数，用来做for循环
        Integer logCount = sysOperLogMapper.selectCount(null);
        //查询所有数据列表
        List<SysOperLog> sysOperLogList = sysOperLogMapper.selectList(null);
        //查询日志数据，提供给Excel模板文件

        InputStream in = SysOperLogServiceImpl.class.getClassLoader().getResourceAsStream("template/操作日志.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheetAt(0);

            //修改后面数据
            for (int i = 0; i < logCount; i++) {
                //准备明细数据
                SysOperLog sysOperLog = sysOperLogList.get(i);
                XSSFRow row = sheet.getRow(1 + i);
                row.getCell(0).setCellValue(sysOperLog.getOperId());
                row.getCell(1).setCellValue(sysOperLog.getTitle());
                if (sysOperLog.getBusinessType() == 0) {
                    row.getCell(2).setCellValue("其他");
                }
                if (sysOperLog.getBusinessType() == 1) {
                    row.getCell(2).setCellValue("新增");
                }
                if (sysOperLog.getBusinessType() == 2) {
                    row.getCell(2).setCellValue("修改");
                }
                if (sysOperLog.getBusinessType() == 3) {
                    row.getCell(2).setCellValue("删除");
                }
                row.getCell(3).setCellValue(sysOperLog.getMethod());
                row.getCell(4).setCellValue(sysOperLog.getRequestMethod());
                if (sysOperLog.getOperatorType() == 0) {
                    row.getCell(5).setCellValue("其他");
                }
                if (sysOperLog.getOperatorType() == 1) {
                    row.getCell(5).setCellValue("后台用户");
                }
                if (sysOperLog.getOperatorType() == 2) {
                    row.getCell(5).setCellValue("手机端用户");
                }
                row.getCell(6).setCellValue(sysOperLog.getOperName());
                row.getCell(7).setCellValue(sysOperLog.getDeptName());
                row.getCell(8).setCellValue(sysOperLog.getOperUrl());
                row.getCell(9).setCellValue(sysOperLog.getOperIp());
                row.getCell(10).setCellValue(sysOperLog.getOperLocation());
                row.getCell(11).setCellValue(sysOperLog.getOperParam());
                row.getCell(12).setCellValue(sysOperLog.getJsonResult());
                if (sysOperLog.getStatus() == 0) {
                    row.getCell(13).setCellValue("正常");
                }
                if (sysOperLog.getStatus() == 1) {
                    row.getCell(13).setCellValue("异常");
                }
                row.getCell(14).setCellValue(sysOperLog.getErrorMsg());
                row.getCell(15).setCellValue(sysOperLog.getOperTime());
            }
            //通过输出流将文件下  载到客户端浏览器中
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            outputStream.flush();
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success("操作日志.xlsx");
    }
//@Override
//public AjaxResult export(List<Long> operIds) {
//    List<SysOperLog> logList = sysOperLogMapper.selectBatchIds(operIds);
//    ExcelUtil excelUtil = new ExcelUtil<>(SysOperLog.class);
//    return excelUtil.exportExcel(logList,"operLog");
//}
}
